package code.wrtp.packets;

import code.exceptions.BadPduFormatException;
import code.wrtp.FrameControlType;

/*Class for leaving, entering, re-presenting alert*/
public class MyAlert implements Packet {

	private byte FC; /* Frame control field */
	private short SA; /* Source Address field */
	private short DA; /* Destination address */
	private short myID; /* ID of the ring new node */
	private short RA;

	public MyAlert(byte FC, short SA, short DA, short myID, short RA) {
		this.FC = FC;
		this.SA = SA;
		this.DA = DA;
		this.myID = myID;
		this.RA = RA;
	}

	public byte getFC() {
		return FC;
	}

	public short getSA() {
		return SA;
	}

	public short getDA() {
		return DA;
	}

	public short getMyID() {
		return myID;
	}

	public short getRA() {
		return RA;
	}

	@Override
	public byte[] toBytes() {
		return toString().getBytes();
	}

	@Override
	public String toString() {
		String token = FC + ";" + RA + ";" + DA + ";" + SA + ";" + myID;
		return token;
	}

	@Override
	public void ParseBytes(byte[] pduRaw) throws BadPduFormatException {
		String[] splittedPacket = new String(pduRaw).split(";", 5);

		if (splittedPacket.length != 5) {
			throw new BadPduFormatException("Wrong packet format");
		}

		FC = Byte.parseByte(splittedPacket[0]);
		if ((FC != FrameControlType.ENTERING_ALERT)
				&& (FC != FrameControlType.LEAVING_ALERT)
				&& (FC != FrameControlType.RE_REPRESENTING_ALERT))
			throw new BadPduFormatException("Wrong packet format");
		RA = Short.parseShort(splittedPacket[1]);
		DA = Short.parseShort(splittedPacket[2]);
		SA = Short.parseShort(splittedPacket[3]);
		myID = Short.parseShort(splittedPacket[4]);
	}
}
